package com.ubao.network;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import android.util.Log;

import com.ubao.activity.MyApp;
import com.ubao.network.resp.CommonResponse;
import com.ubao.network.resp.NewInfoResponse;
import com.ubao.network.resp.SpecialResponse;
import com.ubao.network.resp.TradeResponse;
import com.ubao.network.test.SpeedTest;
import com.ubao.util.log.Logger;



public class HttpClient {

	private static final String TAG = "HttpClient";

	// 注: HttpsConnection继承自HttpConnection
	private HttpConnection conn = null;
	private String resBody;
	public String getResBody() {
		return resBody;
	}

	public int getResCode() {
		return resCode;
	}

	private int resCode;

	public HttpConnection getConn() {
		return conn;
	}

	private InputStream inputStream = null;

	private OutputStream outputStream = null;

	private int mTimeOut = 100000;

	public HttpClient() {
	}

	public HttpClient(int _msgId) {
	}

	public HttpClient(int _msgId, int timeout) {
		this.mTimeOut = timeout;
	}

	private boolean getResponse(RequestInterface subRequest,
			ResponseInterface response) throws Exception {
		try {
			SpeedTest.StartAnaly();
			
			makeConnection(subRequest.getUrl());
			setProperty(subRequest);
			setContent(subRequest);
			final int responseCode = conn.getResponseCode();
			Logger.v(TAG, "the responseCode is:" + responseCode);
				makeInputStream(responseCode);

				final boolean isCmwap;
				final String netType = Connector.NetType(MyApp.getMyApp());
				if (netType != null
						&& (netType.equalsIgnoreCase("cmwap") || netType
								.equalsIgnoreCase("uniwap"))) {
					isCmwap = true;
				} else {
					isCmwap = false;
				}

				response.setData(conn.getHttpURLConnection(), inputStream,
						subRequest, isCmwap);
				SpeedTest.EndAnaly();
				return true;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			cleanup();
		}
	}

	public ResponseInterface getResponse(RequestInterface request)
			throws Exception {
		if (request == null) {
			return null;
		}

		ResponseInterface resp = createResponse(request);
		if (resp == null) {
			return null;
		}

		final List<RequestInterface> requestList = new LinkedList<RequestInterface>();
		findRequests(requestList, request);

		final int len = requestList.size();
		for (int i = 0; i < len; i++) {
			if (!getResponse(requestList.get(i), resp)) {
				return null;
			}
		}

		return resp;
	}

	private static ResponseInterface createResponse(RequestInterface request) {
		final byte type = request.getType();
		if (type == RequestInterface.TYPE_SPECIAL) {
			return new SpecialResponse();
		} else if (type == RequestInterface.TYPE_COMMON) {
			return new CommonResponse();
		} else if (type == RequestInterface.TYPE_INFO) {
			return new NewInfoResponse();
		} else if (type == RequestInterface.TYPE_TRADE) {
			return new TradeResponse();
		}

		return null;
	}

	private static void findRequests(List<RequestInterface> list,
			RequestInterface request) {
		final List<RequestInterface> subRequests = request.getSubRequests();
		if (subRequests == null) {
			list.add(request);
			return;
		}

		final int len = subRequests.size();
		for (int i = 0; i < len; i++) {
			findRequests(list, subRequests.get(i));
		}
	}

	private void makeConnection(final String url) {
		String tmpUrl = url;
		if (url == null) {
			tmpUrl = MyApp.HTTP_URL_LICAI;
		}
		if(!tmpUrl.startsWith("http")){
			tmpUrl="http://"+tmpUrl;
		}
		
		Logger.v(TAG, "Request Url:" + tmpUrl);
		conn = (HttpConnection) Connector.open( tmpUrl,
				Connector.READ_WRITE, mTimeOut);
	}

	private void makeInputStream(int resCode) throws Exception {
		this.resCode=resCode;
		inputStream = resCode==200?conn.openInputStream():conn.openErrorInputStream();
	}

	private void makeOutputStream() throws Exception {
		outputStream = conn.openOutputStream();
	}

	/**
	 * 参数设置
	 * 
	 * @throws Exception
	 */
	private void setProperty(RequestInterface request) throws Exception {
		final Hashtable table = request.getRequestProperty();
		if (table != null) {
			Enumeration keys = table.keys();
			while (keys.hasMoreElements()) {
				String key = (String) keys.nextElement();
				String value = (String) table.get(key);
				conn.setRequestProperty(key, value);
			}
		}
	}

	public void setContent(RequestInterface request) throws Exception {
		try {
			final byte[] content = request.getContent();
			if (content != null) {
				if (conn.getRequestProperty("Content-Type") == null) {
					final int contentLength = request.getContentLength();
					conn.setRequestProperty("Content-Type",
							"application/x-www-form-urlencoded");
					conn.setRequestProperty("Content-Length",
							Integer.toString(contentLength));
				}
				// 方式设置
				conn.setRequestMethod(HttpConnection.POST);
				makeOutputStream();
				outputStream.write(content);
				String BOUNDARY = request.getBoundary();  
				String PREFIX = "--" , LINEND = "\r\n";    
				String MULTIPART_FROM_DATA = "multipart/form-data";    
				String CHARSET = "UTF-8";   
				Map<String, File> files = request.getFiles();
				if(files!=null){
					// 发送文件数据    
					if(files!=null)    
					for (Map.Entry<String, File> file: files.entrySet()) {    
					StringBuilder sb1 = new StringBuilder();    
					sb1.append(PREFIX);    
					sb1.append(BOUNDARY);    
					sb1.append(LINEND);    
					sb1.append("Content-Disposition: form-data; name=\"pic\"; filename=\""+file.getKey()+"\""+LINEND);    
					//sb1.append("Content-Type: application/octet-stream; charset="+CHARSET+LINEND);    
					sb1.append("Content-Type: image/jpg; charset="+CHARSET+LINEND); 
					sb1.append("Content-Transfer-Encoding: binary" + LINEND);
					sb1.append(LINEND);  
					
					Log.d("aa", "sb1-->" + sb1.toString());
					outputStream.write(sb1.toString().getBytes());  
					
					try {
						InputStream is = new FileInputStream(file.getValue());    
						byte[] buffer = new byte[1024];    
						int len = 0;    
						while ((len = is.read(buffer)) != -1) {    
							outputStream.write(buffer, 0, len);  
						Log.d("aa", "sb1-->" + len);
						}    
						  
						is.close();
					} catch (Exception e) {
						e.printStackTrace();
					}    
					outputStream.write(LINEND.getBytes());    
					}    
					  
					//请求结束标志    
					byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();  
					
					outputStream.write(end_data);    
					outputStream.flush(); 
				}
			
				// outputStream.flush();//不要使用，会导致编码变成 chunked
			} else {
				if (Double.valueOf(android.os.Build.VERSION.SDK) >= 14) {
					// 4.0以上setDoOutput一定要设置成false,不然GET方法会自动转成POST
					conn.getHttpURLConnection().setDoOutput(false);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}

	}

	public void cleanup() {
		try {
			if (inputStream != null) {
				inputStream.close();
				inputStream = null;
			}
			if (outputStream != null) {
				outputStream.close();
				outputStream = null;
			}
			if (conn != null) {
				conn.close();
				conn = null;
			}
		} catch (Exception e) {
			// e.printStackTrace();
		}
	}
}
